package org.dsapr.codegen.registry;

import org.dsapr.codegen.common.CodeGenerateProcessor;
import org.dsapr.codegen.processor.MyCodeGenerateProcessor;

import java.lang.annotation.Annotation;
import java.util.*;

/** 加载所有 processor，识别 annotation 标记 */
public class ProcessorRegistry {

    private static Map<String, ? extends CodeGenerateProcessor> processorMapping;

    private ProcessorRegistry() {
        throw new UnsupportedOperationException();
    }

    /**
     * @return: {@link Set< String>} 注解集合
     */
    public static Set<String> getAnnotations() {
        return processorMapping.keySet();
    }

    /**
     * @Description: 获取代码处理器
     * @Param: [annotationName] 注解名称
     * @return: {@link MyCodeGenerateProcessor} 代码处理器
     */
    public static CodeGenerateProcessor getProcessor(String annotationName) {
        return processorMapping.get(annotationName);
    }

    /** 初始化时加载所有 processor **/
    public static void loadProcessors() {
        Map<String, CodeGenerateProcessor> processorMapping = new LinkedHashMap<>();
        ServiceLoader<CodeGenerateProcessor> processors =
                ServiceLoader.load(CodeGenerateProcessor.class, CodeGenerateProcessor.class.getClassLoader());
        Iterator<CodeGenerateProcessor> iterator = processors.iterator();
        while (iterator.hasNext()) {
            CodeGenerateProcessor next = iterator.next();
            Class<? extends Annotation> annotation = next.getAnnotation();
            processorMapping.put(annotation.getName(), next);
        }
        ProcessorRegistry.processorMapping = processorMapping;
    }
}
